package cn.edu.zafu.bigdata.zengyadian;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) {
        try {
            // 创建服务器套接字，监听指定端口
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务器已启动，等待客户端连接...");

            // 接受客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接： " + clientSocket.getInetAddress());

            // 获取输入输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            while (true) {
                // 读取客户端发送的消息
                String clientMessage = in.readLine();
                if (clientMessage == null) {
                    break;
                }
                System.out.println("客户端发来消息： " + clientMessage);

                // 回复客户端消息
                String serverReply = "已收到你的消息： " + clientMessage;
                out.println(serverReply);
            }

            // 关闭连接
            clientSocket.close();
            serverSocket.close();
            System.out.println("与客户端的连接已关闭。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}